﻿using System;
using System.Security.Cryptography;
using System.Text;
using Taxhui.Utils.IOUtils;

namespace Taxhui.Utils.CryptUtils
{
    public static class MD5Crypt
    {
        #region MD5加密
        private static string MD32Crypt(string txt, Encoding sEncode = null)
        {
            try
            {
                sEncode = sEncode ?? Encoding.UTF8;
                byte[] orgByte = sEncode.GetBytes(txt);
                return DataUtil.ByteToStr(MD5EnCrypt(orgByte));
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static byte[] MD5EnCrypt(byte[] data)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] toByte = md5.ComputeHash(data);
            md5.Clear();
            md5.Dispose();
            return toByte;
        }
        /// <summary>
        /// 带盐32位MD5加密
        /// </summary>
        /// <param name="txt">原文</param>
        /// <param name="sault">盐</param>
        /// <param name="sEncode">编码</param>
        /// <returns></returns>
        public static string MD32Crypt(string txt, string sault = "", Encoding sEncode = null)
        {
            try
            {
                string s = MD32Crypt(txt, sEncode);
                if (!string.IsNullOrEmpty(sault))
                {
                    s = MD32Crypt(s + sault, sEncode);
                }
                return s;
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static string MD16Crypt(string txt, string sault = "", Encoding sEncode = null)
        {
            sEncode = sEncode ?? Encoding.UTF8;
            string pass = MD32Crypt(txt, sEncode);
            if (string.IsNullOrEmpty(sault))
            {
                //不加盐
                return pass.Substring(8, 16);
            }
            else
            {
                pass += sault;
                pass = MD32Crypt(pass, sEncode);
                return pass.Substring(8, 16);
            }
        }
        #endregion
    }
}
